{% extends 'wanplus/wangwangba/base_nav_frame.html' %}
{% load staticfiles %}
{% block content %}
  <p>编排</p>
  <div>
    <div class="panel panel-default">
      <div class="panel-heading">
        <h4 class="wb-panel-wigdet">编排清单</h4>
        <div class="wb-panel-wigdet-right">
          <button class="btn btn-default" type="button" id="layout-edit-btn">
            <span class="fa fa-pencil-square-o" style="margin-right: 4px"></span>编辑</button>
          <button class="btn btn-success" type="button" id="layout-save-btn" style="display: none;">
            <span class="fa fa-floppy-o" style="margin-right: 4px"></span>保存</button>
        </div>
        <div class="clearfix"></div>
      </div>
      <table class="table table-hover table-striped" id="wwb-layout-list"></table>
    </div>
  </div>
{% endblock %}
{% block jsscript %}
  <script type="text/javascript">
  (function($) {

    var EditState = function() {
    };
    EditState.prototype = {
      editable : false
      , stateChangeListener : []
      , setEditable : function(ed) {
        if (ed !== this.editable) {
          var old = this.editable;
          this.editable = ed;
          if (this.stateChangeListener) {
            for (var i in this.stateChangeListener) {
              this.stateChangeListener[i]["onStateChanged"].apply(this, [this.editable, old]);
            }
          }
        }
      }
      , isEditable : function () {
        return this.editable;
      }
      , setOnStateChangeListener : function(listener) {
        if ($.isFunction(listener)) {
          var self = this;
          this.stateChangeListener.push({
            o : self
            , l : listener
            , onStateChanged : function(newState, oldState) {
              this.l.apply(this.o, [newState, oldState])
            }
          });
        } else if (typeof listener === 'object'
            && listener.hasOwnProperty("onStateChanged")
            && $.isFunction(listener["onStateChanged"])) {
          this.stateChangeListener.push(listener);
        }
      }
    };

    var globalEditState = new EditState();
    globalEditState.setEditable(false);

    $.fn.editableSelector = function (selectList, currentValue, editable) {
      var self = this;

      var _selectList = selectList;
      var _currentValue = currentValue;
      var _currentTarget = null;
      var _selectChangeListener = null;

      var init = function(isEditable) {
        reset(isEditable);
      };

      var reset = function(isEditable) {
        if (_currentTarget) {
          $(_currentTarget).remove();
        }
        if (isEditable) {
          var select = $("<select />");
          for (var sv in _selectList) {
            var option = sv == _currentValue ? $("<option selected/>") : $("<option />");
            option.attr("value", sv).text(_selectList[sv]);
            select.append(option);
          }
          select.change(function(e) {
            _currentValue = select.val();
            if ($.isFunction(_selectChangeListener)) {
              _selectChangeListener.apply(self, [e, _currentValue]);
            }
          });
          $(self).html(select);
        } else {
          $(self).html(_selectList[_currentValue]);
        }
      };

      var initState = false;
      if (editable) {
        initState = editable.isEditable()
      }
      init(initState);

      var o = {
        onStateChanged : function(newState, oldState) {
          reset(newState);
        }
        ,
        setOnSelectChangeListener : function(listener) {
          _selectChangeListener = listener;
        }
      };
      if (editable) {
        editable.setOnStateChangeListener(o);
      }
      return o;
    };

    var STATE = [
      "待处理", "预发布", "已上线", "已下线"
    ];

    $(document).ready(function(e) {

      var selectList = {
      {% for category in categorys%}
        {% if forloop.first %}
          "{{ category.code }}" : "{{ category.name }}"
        {% else %}
          , "{{ category.code }}" : "{{ category.name }}"
        {% endif %}
      {% endfor %}
      };

      var changedData = [];

      var layoutTable = $("#wwb-layout-list").table({
        columnKeys : ["code", "name", "category", "state", "operations"]
        , columnNames : ["内容编号", "名称", "栏目", "状态", "操作"]
        , columnBody : function(key, value, data) {
          switch (key) {
            case 'category':
                var span = $("<span />");
                var selector = $(span).editableSelector(selectList, value,
                    parseInt(data["state"]) != 2 ? globalEditState : new EditState());
                selector.setOnSelectChangeListener(function(e, value) {
                  changedData.push({
                    "token": data["token"]
                    , "category": value
                  })
                });
              return span;
            case 'state':
                switch (parseInt(value)) {
                 case 0:
                 case 1:
                 case 2:
                 case 3:
                   return STATE[parseInt(value)];
                 default:
                   return ''
                }
            case 'operations':
                var state = parseInt(data["state"]);
                var btn = $('<button />').addClass("btn btn-xs");
                btn.css({
                  marginRight : "8px"
                });
                switch (state) {
                  case 0:
                      btn.addClass("btn-info");
                      btn.text("预览");
                      btn.data("api", "./layout/preview");
                    break;
                  case 1:
                      btn.addClass("btn-success");
                      btn.text("上线");
                      btn.data("api", "./layout/release");
                    break;
                  case 2:
                      btn.addClass("disabled");
                      btn.text("上线");
                    break;
                  default:
                    break;
                }
                btn.data("state", state);
                btn.click(function(e) {
                  var self = $(this);
                  var api = self.data("api");
                  var s = self.data("state");

                  self.empty();
                  var spinner = $('<span />').addClass("fa fa-spinner fa-spin fa-lg");
                  self.addClass("disabled");
                  self.append(spinner);

                  $.ajax({
                    url : api + "/" + data["token"]
                    , type : "GET"
                    , dataType : "json"
                    , success : function (data) {
                      if (data && data.resultCode == 1) {
                        $.wUtils.reload();
                      } else {
                        self.empty();
                        self.removeClass("disabled");
                        switch (s) {
                          case 0:
                            self.text("预览");
                            break;
                          case 1:
                            self.text("上线");
                            break;
                          default:
                        }
                      }
                    }
                    , error : function () {
                      self.empty();
                      self.removeClass("disabled");
                      switch (s) {
                        case 0:
                          self.text("预览");
                          break;
                        case 1:
                          self.text("上线");
                          break;
                        default:
                      }
                    }
                  })
                });
                var delBtn = $('<button />').addClass("btn btn-xs btn-danger");
                delBtn.text("删除");

                var p = $('<div />');
                p.append(btn);
{#                p.append(delBtn);#}

              return p;
            default :
              return value;
          }
        }
      });

      $.ajax({
        url : "./layout/list"
        , type : "get"
        , dataType : "json"
        , success : function (data) {
          if (data.resultCode == 1) {
            layoutTable.load($.wUtils.getListData(data));
          }
        }
        , error : function () {}
      });

      $("#layout-edit-btn").click(function(e) {
        globalEditState.setEditable(true);
        $(this).hide();
        $("#layout-save-btn").show();
      });

      $("#layout-save-btn").click(function(e) {
        globalEditState.setEditable(false);
        var layout_data = [];
        for (var i in changedData) {
          layout_data.push(JSON.stringify(changedData[i]));
        }
        $.ajax({
          url : "./layout/save"
          , type : "post"
          , data : {
            layout : layout_data
          }
          , dataType : "json"
          , success : function (data) {
            $(this).hide();
            $("#layout-edit-btn").show();
          }.bind(this)
          , error : function () {
            $(this).hide();
            $("#layout-edit-btn").show();
          }.bind(this)
        })
      });
    });
  })(jQuery);

  </script>
{% endblock %}